using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Kiwi.Node.Modules
{
    public class LibModuleResolver : IModuleResolver
    {
        public LibModuleResolver(Assembly assembly, string @namespace)
        {
            Assembly = assembly;
            Namespace = @namespace;

            var prefix = Namespace + ".";
            ModuleResources = (
                                  from resourceName in Assembly.GetManifestResourceNames()
                                  where resourceName.StartsWith(prefix)
                                  where resourceName.EndsWith(".js")
                                  let moduleName = resourceName.Split('.').Reverse().Skip(1).First()

                                  select
                                      new
                                          {
                                              ModuleName = moduleName,
                                              ResourceName = resourceName
                                          }).
                ToDictionary(o => o.ModuleName, o => o.ResourceName);
        }

        public Assembly Assembly { get; private set; }
        public string Namespace { get; private set; }
        public Dictionary<string, string> ModuleResources { get; private set; }

        #region IModuleResolver Members

        public IResolvedModule TryResolveDynamic(IApplication application, string folder, string moduleName)
        {
            string resourceName;
            if (ModuleResources.TryGetValue(moduleName, out resourceName))
            {
                return
                    new ResolvedModule(c => new Module(application, new EmbeddedScriptSource(resourceName)).Exports)
                        {
                            Key = moduleName,
                            Path = ""
                        };
            }
            return null;
        }

        #endregion
    }
}